<template>
  <el-cascader
      ref="selectDeptUser"
      style="width: 100%"
      v-model="selectedValues"
      :options="filteredTreeData"
      :props="treeProps"
      :show-all-levels="false"
      filterable
      :disabled="disabled"
      clearable
      @change="handleChange"
  />
</template>

<script setup>

import {deptTreeSelectUser} from '@/api/system/user'
import {nextTick, onMounted, reactive, ref, watch} from 'vue'

// 定义组件 props
const props = defineProps({
  options: {
    type: Object,
    default: () => ({})
  },
  // 将value改为modelValue以符合Vue3的v-model规范
  modelValue: {
    type: [Array, String, Number],
    default: () => ''
  },
  resultProps: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  },
  rootId: {
    type: [String, Number],
    default: null
  }
})

// 定义组件 emits
const emit = defineEmits(['update:modelValue', 'change'])

// 组件状态
const selectDeptUser = ref(null)
// 使用modelValue作为初始值
const selectedValues = ref(props.modelValue)
const originalTreeData = ref([])
const filteredTreeData = ref([])


// 树形配置
const treeProps = reactive({
  value: 'id',
  label: 'name',
  emitPath: false,
  leaf: 'isLeaf',
  multiple: false
})

const resultPropsValue = reactive({
  userId: 'userId',
  name: 'name',
  id: 'id'
})



watch(
    () => props.modelValue,
    (newVal) => {
      let convertedVal = newVal;
      if (typeof newVal === 'number' && !isNaN(newVal)) {
        convertedVal = String(newVal);
      }
      selectedValues.value = convertedVal;
    },
    {
      deep: true,
      immediate: true
    } // 添加深度监听配置
)


// 转换值为字符串类型


const filterTreeData = () => {
  if (!originalTreeData.value.length) return

  if (props.rootId) {
    // 查找指定节点的子节点
    const filtered = findNodeAndGetChildren(originalTreeData.value, props.rootId)
    filteredTreeData.value = filtered || []
  } else {
    // 不指定 rootId 时展示全部数据
    filteredTreeData.value = originalTreeData.value
  }
}

// 监听 selectedValues 变化，触发 update:modelValue 事件（Vue3的v-model更新方式）
watch(
    () => selectedValues.value,
    (newVal) => {
      emit('update:modelValue', newVal)
    }
)

// 监听 rootId 变化，重新过滤数据
watch(
    () => props.rootId,
    () => {
      filterTreeData()
    },
    {immediate: true}
)

// 监听原始数据变化，重新过滤
watch(
    () => originalTreeData.value,
    () => {
      filterTreeData()
    }
)


// 初始化
onMounted(() => {
  init()
})

// 初始化方法
const init = () => {
  // 合并 resultProps
  Object.assign(resultPropsValue, props.resultProps)
  // 合并 treeProps 配置
  Object.assign(treeProps, props.options)
  deptTreeSelectUser().then((res) => {
    originalTreeData.value = res
  })
}

// 处理选择变化
const handleChange = (value) => {
  nextTick(() => {
    emit('change', value)
  })
}

// 递归查找指定 ID 的节点并返回其 children
const findNodeAndGetChildren = (treeData, targetId) => {
  // 确保 targetId 类型一致
  const targetIdStr = String(targetId)
  for (const node of treeData) {
    if (String(node.id) === targetIdStr) {
      return node.children || []
    }
    if (node.children && node.children.length) {
      const result = findNodeAndGetChildren(node.children, targetIdStr)
      if (result) {
        return result
      }
    }
  }
  return null
}
</script>

<style scoped></style>
